package com.hxzy.action;

import java.io.File;
import java.util.Arrays;

import org.apache.commons.lang3.StringUtils;

import com.hxzy.entity.User;
import com.hxzy.service.AttachmentService;
import com.hxzy.service.AttachmentServiceImpl;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class UploadAction extends ActionSupport {

	private static final long serialVersionUID = -7094299355706269739L;
	private String filename;
	private File file;
	private String savePath;
	private String fileContentType;
	private AttachmentService attachmentService=new AttachmentServiceImpl();
	
	@Override
	public String execute() throws Exception {
		File srcFile=file;
		File destFile=new File(savePath+File.separator+filename);
		User sessionUser=(User) ActionContext.getContext().getSession().get("user");
		String downloadurl=attachmentService.Upload(srcFile, fileContentType, destFile, sessionUser.getId(), 0);
		if(!StringUtils.isEmpty(downloadurl)){
			addActionError("文件上传成功,下载路径");
			addActionMessage(downloadurl);
			return SUCCESS;
		}
		addActionError("文件上传失败");
		return INPUT;
	}

	@Override
	public void validate() {
		// TODO Auto-generated method stub
		if(StringUtils.isBlank(filename)){
			addFieldError("filename", "名字不能为空");
		}if(file==null||file.length()==0){
			addFieldError("file", "文件不能为空");
		}
		File savePathFile = new File(savePath);
		if (StringUtils.isBlank(savePath) || !savePathFile.exists() || !savePathFile.canWrite()) {
			addActionError("请配置服务器上传目录");
		}
	}


	
	public String getFileContentType() {
		return fileContentType;
	}

	public void setFileContentType(String fileContentType) {
		this.fileContentType = fileContentType;
	}

	public AttachmentService getAttachmentService() {
		return attachmentService;
	}

	public void setAttachmentService(AttachmentService attachmentService) {
		this.attachmentService = attachmentService;
	}

	public String getFilename() {
		return filename;
	}

	public void setFilename(String filename) {
		this.filename = filename;
	}

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public String getSavePath() {
		return savePath;
	}

	public void setSavePath(String savePath) {
		this.savePath = savePath;
	}

	
	
}
